const redlock = require('./redlockConfig');

async function performTaskWithLock(resource) {
  let lock;
  try {


    
    // Acquire a lock on the resource
    lock = await redlock.lock(`locks:${resource}`, 5000); // Lock for 10 seconds

    // Perform your task here
    console.log(`Lock acquired for resource: ${resource}`);
    // Simulate task duration
    await new Promise(resolve => setTimeout(resolve, 10000));
    console.log(`Task completed for resource: ${resource}`);

  } catch (error) {
    console.error('Failed to acquire lock:', error);
  } finally {
    if (lock) {
      try {
        await lock.unlock();
        console.log(`Lock released for resource: ${resource}`);
      } catch (releaseError) {
        console.log(releaseError typeof)
        console.error('Failed to release lock:', releaseError);
      }
    }
  }
}

// Example usage
performTaskWithLock('my-resource');